#!/usr/bin/env python3
"""
初始化数据库数据
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.db.database import SessionLocal
from app.models.user import User
from app.models.category import Category
from app.models.tag import Tag
from app.core.security import get_password_hash

def init_data():
    db = SessionLocal()
    try:
        # 创建管理员用户
        admin_user = db.query(User).filter(User.username == "admin").first()
        if not admin_user:
            admin_user = User(
                username="admin",
                email="admin@example.com",
                hashed_password=get_password_hash("admin123"),
                is_superuser=True,
                is_active=True
            )
            db.add(admin_user)
            print("✅ 创建管理员用户: admin/admin123")
        
        # 创建测试分类
        categories_data = [
            {"name": "电子产品", "description": "各种电子设备", "slug": "electronics"},
            {"name": "服装", "description": "时尚服装", "slug": "clothing"},
            {"name": "家居", "description": "家居用品", "slug": "home"},
            {"name": "图书", "description": "各类图书", "slug": "books"},
        ]
        
        for cat_data in categories_data:
            existing_cat = db.query(Category).filter(Category.slug == cat_data["slug"]).first()
            if not existing_cat:
                category = Category(**cat_data)
                db.add(category)
                print(f"✅ 创建分类: {cat_data['name']}")
        
        # 创建测试标签
        tags_data = [
            {"name": "热门", "color": "#EF4444"},
            {"name": "新品", "color": "#10B981"},
            {"name": "促销", "color": "#F59E0B"},
            {"name": "推荐", "color": "#3B82F6"},
        ]
        
        for tag_data in tags_data:
            existing_tag = db.query(Tag).filter(Tag.name == tag_data["name"]).first()
            if not existing_tag:
                tag = Tag(**tag_data)
                db.add(tag)
                print(f"✅ 创建标签: {tag_data['name']}")
        
        db.commit()
        print("✅ 数据初始化完成!")
        
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    init_data() 